<!--
  * 出库单
  *
  * @Author:    zzx
  * @Date:      2025-08-13 15:17:33
  * @Copyright  zzx
-->
<template>
  <a-drawer
      :title="`${cuttingInfo.cuttingName}`"
      :width="1200"
      :open="visibleFlag"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
      destroyOnClose
  >
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
            <a-form-item label="联系人信息" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.keywords" placeholder="联系人信息" />
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="onSearch">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button @click="toAdd" type="primary" size="small">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button>
                <a-button @click="confirmBatchDelete" type="primary" danger size="small" :disabled="selectedRowKeyList.length == 0">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table
            size="small"
            :scroll="{ y: 800 }"
            :dataSource="tableData"
            :columns="columns"
            rowKey="outboundId"
            bordered
            :loading="tableLoading"
            :pagination="false"
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
            <template #bodyCell="{ text, record, column }">

                <template v-if="column.dataIndex === 'outboundDateId'">
                  <a @click="toDetail(record.outboundId)">{{record.outboundDateId}}</a>
                </template>


              <template v-if="column.dataIndex === 'outboundComplete'">
                <div>
                  <a-tag v-if="text===1" color="green">是</a-tag>
                  <a-tag v-else color="red">否</a-tag>
                </div>
              </template>

                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button @click="toEdit(record.outboundId)" type="link">编辑</a-button>
                        <a-button @click="exportExcl(record.outboundId)" type="link">导出</a-button>
                        <a-button @click="onDelete(record)" danger type="link">删除</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination
                showSizeChanger
                showQuickJumper
                show-less-items
                :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize"
                v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize"
                :total="total"
                @change="queryData"
                @showSizeChange="queryData"
                :show-total="(total) => `共${total}条`"
            />
        </div>

    </a-card>
  </a-drawer>
</template>
<script setup>
    import { reactive, ref, onMounted } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { outboundInfoApi } from '/@/api/business/project/outbound-info-api';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import {useRoute, useRouter} from "vue-router";
    import _ from "lodash";


    // const route = useRoute();
    //
    // let projectId = ref();
    // let quotationId = ref();
    // let cuttingId = ref();
    // onMounted(() => {
    //   if (route.query.projectId) {
    //     projectId.value = Number(route.query.projectId);
    //   }
    //   if (route.query.quotationId) {
    //     quotationId.value = Number(route.query.quotationId);
    //   }
    //   if (route.query.cuttingId) {
    //     cuttingId.value = Number(route.query.cuttingId);
    //   }
    // });

    // ------------------------ 事件 ------------------------
    const emits = defineEmits(['reloadList']);

    // ------------------------ 显示与隐藏 ------------------------
    // 是否显示
    const visibleFlag = ref(false);

    // ---------------------------- 表格列 ----------------------------

    const columns = ref([
        {
            title: '出库编号',
            dataIndex: 'outboundDateId',
            ellipsis: true,
        },
        {
            title: '收货联系人',
            dataIndex: 'receiveUser',
            ellipsis: true,
        },
        {
            title: '收货手机号',
            dataIndex: 'receiveTel',
            ellipsis: true,
        },
        {
            title: '司机联系人',
            dataIndex: 'driverUser',
            ellipsis: true,
        },
        {
            title: '司机手机号',
            dataIndex: 'driverTel',
            ellipsis: true,
        },
        {
            title: '是否完成',
            dataIndex: 'outboundComplete',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: 90,
        },
    ]);


    let cuttingInfo = reactive({});
    // 展示来源： 下料列表显示对应出库列表
    function show(rowData) {
      if (rowData && !_.isEmpty(rowData)) {
        visibleFlag.value = true;
        Object.assign(cuttingInfo, rowData);
        queryData()
      } else {
        message.error("打开出错, 请联系管理员")
      }
    }

    function onClose() {
      visibleFlag.value = false;
    }
    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
        keywords: undefined, //联系人信息
        pageNum: 1,
        pageSize: 10,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);

    // 重置查询条件
    function resetQuery() {
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }

    // 搜索
    function onSearch(){
      queryForm.pageNum = 1;
      queryData();
    }

    // 查询数据
    async function queryData() {
        tableLoading.value = true;
        try {
            if (cuttingInfo.cuttingId != null) {
              queryForm.cuttingId = cuttingInfo.cuttingId
            }
            let queryResult = await outboundInfoApi.queryPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }

    // ---------------------------- 添加/修改 ----------------------------
    const formRef = ref();

    function showForm(data) {
        formRef.value.show(data);
    }


    // ---------------------------- 单个删除 ----------------------------
    //确认删除
    function onDelete(data){
        Modal.confirm({
            title: '提示',
            content: '确定要删除选吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestDelete(data);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求删除
    async function requestDelete(data){
        SmartLoading.show();
        try {
            let deleteForm = {
                goodsIdList: selectedRowKeyList.value,
            };
            await outboundInfoApi.delete(data.outboundId);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    const selectedRowKeyList = ref([]);

    function onSelectChange(selectedRowKeys) {
        selectedRowKeyList.value = selectedRowKeys;
    }

    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await outboundInfoApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    let router = useRouter();
    function toDetail(outboundId) {
      router.push({ path: '/erp/project/components/outbound-info-detail',
        query: { cuttingId: cuttingInfo.cuttingId, outboundId: outboundId} });
    }

    function toAdd() {
      router.push({ path: '/erp/project/components/outbound-info-form',
        query: { cuttingId: cuttingInfo.cuttingId } });
    }

    function toEdit(outboundId) {
      router.push({ path: '/erp/project/components/outbound-info-form',
        query: { cuttingId: cuttingInfo.cuttingId, outboundId: outboundId } });
    }

    async function exportExcl(outboundId) {
      try {
        let result = await outboundInfoApi.exportExcl(outboundId);
      } catch (error) {
        smartSentry.captureError(error);
      } finally {
        SmartLoading.hide();
      }
    }

    defineExpose({
      show,
    });
</script>
